import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入Vuex仓库
import store from '@/store'

// 二级路由导入
import Home from '@/views/layout/home.vue'
import Category from '@/views/layout/category.vue'
import Cart from '@/views/layout/cart.vue'
import User from '@/views/layout/user.vue'

// 一级路由
import Layout from '@/views/layout'

// 一级路由导入(懒加载---除了Layout全部改造)
const Login = () => import('@/views/login')
const Search = () => import('@/views/search/search.vue')
const List = () => import('@/views/search/list.vue')
const Myorder = () => import('@/views/myorder')
const Pay = () => import('@/views/pay')
const Prodetail = () => import('@/views/prodetail')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      { path: '/home', component: Home },
      { path: '/category', component: Category },
      { path: '/cart', component: Cart },
      { path: '/user', component: User }
    ]
  },
  { path: '/login', component: Login },
  { path: '/search', component: Search },
  { path: '/searchlist', component: List },
  { path: '/myorder', component: Myorder },
  { path: '/pay', component: Pay },
  // 动态路由传参，确认是哪一个商品
  { path: '/prodetail/:id', component: Prodetail }
]

const router = new VueRouter({
  routes
})

// 所有的路由在真正被访问到之前(解析渲染对应组件页面前)，都会先经过全局前置守卫
// 只有全局前置守卫放行了，才会达到对应的页面
// 全局前置导航守卫
// 1. to 往哪里去， 到哪去的路由信息对象  里面有两个关键的属性，path属性：页面路径，fullPath属性：页面路径（带参数的也可以访问到）
// 2. from 从哪里来， 从哪来的路由信息对象
// 3. next() 是否放行
//        如果next()调用，就是放行
//        next(路径) 拦截到某个路径页面

// 定义一个数组，专门用户存放所有需要权限访问的页面
const authUrls = ['/pay', '/myorder']

router.beforeEach((to, from, next) => {
  // console.log(to, from, next)
  // 看to.path是否在authUrls中出现过
  if (!authUrls.includes(to.path)) {
    next()
    return
  }
  // 是权限页面，需要判断token(在vuex仓库封装了getters)
  const token = store.getters.token
  // console.log(token)
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
